package com.manning.readinglist;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ReaderRepository readerRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").access("hasRole('READER')")
                .antMatchers("/mgmt/**").access("hasRole('ADMIN')")
                .antMatchers("/shutdown").access("hasRole('ADMIN')")  // 保护 /shutdown 端点，仅允许拥有 ADMIN 权限的用户访问
                .antMatchers("/metrics", "configprops").access("hasRole('ADMIN')") // 像保护 /shutdown 端点一样仅允许拥有 ADMIN 权限的用户访问其他指定的端点
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true");
    }

    @Override
    protected void configure(
            AuthenticationManagerBuilder auth) throws Exception {
//    auth
//      .userDetailsService(new UserDetailsService() {
//        @Override
//        public UserDetails loadUserByUsername(String username)
//            throws UsernameNotFoundException {
//          UserDetails user = readerRepository.findOne(username);
//          if (user != null) {
//            return user;
//          }
//          throw new UsernameNotFoundException("User '" + username + "' not found.");
//        }
//      })
//      .and()
//      .inMemoryAuthentication()
//        .withUser("manager").password("s3cr3t").roles("ADMIN");

        auth
                .userDetailsService(new UserDetailsService() {  // Reader 身份验证
                    @Override
                    public UserDetails loadUserByUsername(String username)
                            throws UsernameNotFoundException {
                        UserDetails user = readerRepository.findOne(username);
                        if (user != null) {
                            return user;
                        }
                        throw new UsernameNotFoundException(
                                "User '" + username + "' not found.");
                    }
                })
                .and()
                // 新加的内存身份验证中，用户名定义为 admin，密码为 s3cr3t，同时被授予 ADMIN 和 READER 权限。
                .inMemoryAuthentication()
                .withUser("admin").password("s3cr3t")
                .roles("ADMIN", "READER");  // Admin 身份验证
    }

}
